using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace TmxUtil
{
    public class ResXBrowser
    {
        private ResXItemCollection _source;
        Dictionary<string, List<ResXItem>> _cache = new Dictionary<string, List<ResXItem>>();
        private string[] _globalKeys;

        public ResXBrowser(ResXItemCollection items)
        {
            _source = items;
            Parse();
        }

        public string[] GlobalKeys
        {
            get { return _globalKeys; }
        }

        public IEnumerable<ResXItem> GetLocalizations(string globalKey)
        {
            List<ResXItem> list;
            _cache.TryGetValue(globalKey, out list);
            return list;
        }

        public ResXItem GetLocalization(string globalKey, string cultureName)
        {
            List<ResXItem> list;
            _cache.TryGetValue(globalKey, out list);
            if (list == null)
                return null;

            ResXItem found = list.Find(delegate(ResXItem obj) { return obj.ResX.CultureName == cultureName; });
            return found;
        }

        public string GetLocalKey(string globalKey)
        {
            List<ResXItem> list;
            _cache.TryGetValue(globalKey, out list);
            if (list == null)
                return null;

            return list[0].Key;
        }


        void Parse()
        {
            List<ResXItem> items = new List<ResXItem>(_source);

            foreach(ResXItem item in items)
            {
                string gk = item.GlobalKey;
                List<ResXItem> list;
                if (!_cache.TryGetValue(gk, out list))
                {
                    list = new List<ResXItem>();
                    _cache[gk] = list;
                }

                list.Add(item);
            }

            foreach(List<ResXItem> list in _cache.Values)
            {
                list.Sort(delegate(ResXItem x, ResXItem y) { return x.ResX.CultureName.CompareTo(y.ResX.CultureName); });
            }

            _globalKeys = new string[_cache.Count];
            _cache.Keys.CopyTo(_globalKeys, 0);
            Array.Sort(_globalKeys);
        }
    }
}
